#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import codecs
import configparser


class ReadUserConfig:

    def __init__(self):
        # 拿到配置文件的根路径
        current_path = os.path.abspath(os.path.dirname(__file__))
        self._project_path = os.path.dirname(current_path)

        # 以配置的方式读取文件
        cf_1 = configparser.ConfigParser()
        cf_1.read(os.path.join(self._project_path, "base_config.ini"), encoding="utf-8")

        # 获取配置内容
        configuration_file = cf_1.get("configuration", "configuration_file")

        # 判断使用哪份配置文件
        if configuration_file == "user_config.ini":
            self._file_name = "user_config.ini"
            # print("正在使用[user_config.ini]配置文件\n")
        else:
            self._file_name = "user_config_bak.ini"
            # print("正在使用[user_config_bak.ini]配置文件\n")

        # 最终配置文件路径
        self._config_path = os.path.join(self._project_path, self._file_name)

        # 读取文件相关
        fd = open(self._config_path, encoding="utf-8")
        data = fd.read()

        #  remove BOM
        if data[:2] == codecs.BOM_UTF8:
            data = data[2:]
            file = codecs.open(self._config_path, "w")
            file.write(data)
            file.close()
        fd.close()

        self.cf = configparser.ConfigParser()
        self.cf.read(self._config_path, encoding="utf-8")

    def get(self, service_name, key_name):
        """
        获取配置文件的值
        :param service_name: user_config[app][admin][store_app][store_admin]
        :param key_name: 需要的字段
        :return: 返回值
        """
        if type(service_name) != str or type(key_name) != str:
            raise TypeError('service_name,name必须是Str型')
        else:
            try:
                value = self.cf.get(service_name, key_name)
                return value
            except IOError:
                raise (self._file_name + "下找不到" + str(service_name) + "配置")

    def set(self, service_name='[app][admin][store_app][store_admin]', key_name=None, value=''):
        """
        修改或写入配置文件的值
        :param service_name: [app][admin][store_app][store_admin]
        :param key_name: 设置的字段
        :param value: 值
        :return:
        """
        if type(service_name) != str or type(key_name) != str or type(value) != str:
            raise TypeError('service_name,name,value必须是Str型')
        else:
            try:
                self.cf.set(service_name, key_name, value)
            except BaseException:
                raise ValueError('写入配置错误')
        try:
            with open(self._config_path, 'w+') as f:
                self.cf.write(f)
        except IOError:
            raise (self._file_name + "下无" + str(service_name) + "配置，或者设置失败！")


if __name__ == "__main__":
    test = ReadUserConfig()
    phone = test.get("app", "phone")
    print(phone)

    current_dir = os.path.abspath(os.path.dirname(__file__))
    print(os.path.dirname(__file__))
    print(current_dir)
    pro_dir = os.path.dirname(current_dir)
    print(pro_dir)
